package com.viphuli.app.tool.handler;

import org.apache.http.Header;

import android.support.v4.app.Fragment;
import butterknife.ButterKnife;

import com.offroader.R;
import com.offroader.core.IFrag;
import com.offroader.http.MyJsonHttpResponseHandler;
import com.offroader.utils.LogUtils;
import com.offroader.utils.NetUtils;
import com.offroader.utils.NetUtils.NetType;
import com.offroader.utils.ViewUtils;
import com.viphuli.app.tool.bean.PageBaseBean;
import com.viphuli.app.tool.bean.part.AccountUser;
import com.viphuli.app.tool.common.AccessTokenKeeper;
import com.viphuli.app.tool.common.Constants;
import com.viphuli.app.tool.common.MyApp;
import com.viphuli.app.tool.fragment.BaseProgressFragment;

public abstract class MyBaseHttpResponseHandler<Caller, T> extends MyJsonHttpResponseHandler<Caller, T> {

	private boolean showTip;
	private HandlerType handlerType;
	protected Caller caller;
	protected T page;

	public void init(Caller caller) {
		this.caller = caller;

		//依赖注入
		if (caller instanceof Fragment) {
			ButterKnife.bind(this, ((Fragment) caller).getActivity());
		}

	}

	@Override
	public void onStart() {

		if (caller instanceof IFrag) {

			IFrag frag = (IFrag) caller;

			if (!frag.isAdded())
				return;

			//网络或接口异常处理
			if (NetType.TYPE_NONE.equals(NetUtils.checkNet())) {
				netError(frag);
				return;
			}

			if (HandlerType.loading.equals(handlerType)) {

				frag.showLoadDialog();
				frag.notEmpty();

			} else if (HandlerType.waitting.equals(handlerType)) {

				frag.showWaitDialog();

			} else if (HandlerType.refresh.equals(handlerType)) {
			} else if (HandlerType.none.equals(handlerType)) {
			}

		}

	}

	@Override
	public void onSuccess(int statusCode, Header[] headers, String throwable, T obj) {
		IFrag frag = null;
		if (caller instanceof IFrag) {

			frag = (IFrag) caller;

			if (!frag.isAdded()) {
				return;
			}

			if (obj == null) {
				ViewUtils.toast("接口返回数据为空");
				return;
			}

			PageBaseBean basePage = null;
			page = clazz.cast(obj);
			if (page instanceof PageBaseBean) {
				basePage = (PageBaseBean) page;
				if (basePage.isSuccess()) {
					//业务处理
					deal();

				} else {
					//业务异常返回提示用户
					ViewUtils.toast(basePage.getResultMsg());

					//小组不存在
					if (basePage.getResultCode() == Constants.CIRCLE_NOT_EXSIST) {
						//清除本地小组ID
						AccessTokenKeeper tokenKeeper = AccessTokenKeeper.readAccessToken(MyApp.getInstance());

						AccountUser user = tokenKeeper.getUser();
						if (user.getCircleList() != null) {
							user.getCircleList().clear();
						}

						AccessTokenKeeper.keepAccessToken(MyApp.getInstance(), tokenKeeper);
					}
				}

			} else {
				ViewUtils.toast("page类型错误，需使用PageBaseBean及子类");
			}

			if (HandlerType.waitting.equals(handlerType)) {

				if (basePage != null && showTip)
					ViewUtils.toast(basePage.getResultMsg());
			}

			//结束后处理
			afterDeal(frag, obj);

		} else {
			ViewUtils.toast("caller类型错误，需使用BaseProgressFragment及子类");
		}

	}

	@Override
	public void onSuccess(int statusCode, Header[] headers, byte[] responseBytes) {
		super.onSuccess(statusCode, headers, responseBytes);
		LogUtils.info("接口输出|" + new String(responseBytes));
	}

	@Override
	public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonResponse, T page) {
		IFrag frag = null;
		try {

			if (caller instanceof IFrag) {

				frag = (BaseProgressFragment) caller;

				if (!frag.isAdded())
					return;

				//				if (HandlerType.loading.equals(handlerType))
				//					frag.hideLoadDialog();
				//				else if (HandlerType.waitting.equals(handlerType))
				//					frag.hideWaitDialog();

				//				if (statusCode != HttpStatus.SC_OK) {
				//					ViewUtils.toast("服务端异常|" + statusCode);
				//					LogUtils.info("服务端异常返回|" + rawJsonResponse);
				//				}

			}

		} finally {
			LogUtils.info("@@@@@@@@@@@@@@@@onFailure@@" + statusCode);
			afterDeal(frag, page);

		}
	}

	public void setHandlerType(HandlerType handlerType) {
		this.handlerType = handlerType;
	}

	public void setShowTip(boolean showTip) {
		this.showTip = showTip;
	}
	
	public boolean isShowTip() {
		return showTip;
	}

	/**
	 * 业务处理
	 */
	public abstract void deal();

	private void afterDeal(final IFrag frag, T page) {
		if (frag == null || !frag.isAdded())
			return;

		if (HandlerType.loading.equals(handlerType)) {

			frag.hideLoadDialog(true);

		} else if (HandlerType.waitting.equals(handlerType)) {

			frag.hideWaitDialog();

		} else if (HandlerType.refresh.equals(handlerType)) {

			frag.setRefreshing(false);

		} else if (HandlerType.more.equals(handlerType)) {

			frag.setMore(false);

		} else if (HandlerType.none.equals(handlerType)) {
		}

		//异常 - 网络错误视图
		if (page == null || NetType.TYPE_NONE.equals(NetUtils.checkNet())) {
			netError(frag);

		} else {//正常 - 显示业务视图

			if (frag.isShownNetError())
				frag.notEmpty();

		}

	}

	/**
	 * 网络或接口错误
	 * @param frag
	 */
	private void netError(IFrag frag) {

		//界面展示请求失败时显示错误界面
		if (HandlerType.loading.equals(handlerType)) {
			frag.doShowNetError();
		} else {
			ViewUtils.toast(R.string.net_error);
		}

	}

	/**
	 * 处理类型
	 */
	public enum HandlerType {
		loading, //页面加载
		waitting, //操作等待
		refresh, //页面刷新
		more, //更多
		none, //无
	}
}
